<!-- 跑马灯效果 -->
<template>
  <div class="marquee-box">
    <div class="marquee-content" ref="outer">
      <p :class="run ? speed : 'flex-center'">
        <span :style="{ marginRight: run ? '150px' : '0' }" ref="inner">{{ content }}</span>
        <span v-if="run" :style="{ marginRight: run ? '150px' : '0' }"> {{ content }}</span>
      </p>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { nextTick, onMounted, ref, watch } from 'vue'
  const run = ref(false)
  const inner = ref<HTMLElement>()
  const outer = ref<HTMLDivElement>()

  const props = defineProps({
    content: {
      type: [String, Object]
    },
    speed: {
      type: String,
      default: 'slow'
    }
  })

  watch(
    props,
    (val) => {
      if (val.content) {
        setTimeout(() => {
          nextTick(() => {
            let outWidth = outer.value?.clientWidth
            let inWidth = inner.value?.clientWidth
            run.value = (inWidth || 0) > (outWidth || 0) ? true : false
          })
        }, 0)
      }
    },
    {
      deep: true,
      immediate: true
    }
  )

  onMounted(() => {
    nextTick(() => {
      let outWidth = outer.value?.clientWidth
      let inWidth = inner.value?.clientWidth
      run.value = (inWidth || 0) > (outWidth || 0) ? true : false
    })
  })
</script>
<style scoped lang="scss">
  .marquee-box {
    height: 24px;
    line-height: 24px;
    font-size: 12px;
  }
  .marquee-content {
    overflow: hidden;
    width: 100%;
  }
  .marquee-content p {
    display: inline-block;
    white-space: nowrap;
    margin: 0;
    font-size: 0;
  }
  .marquee-content span {
    box-sizing: content-box;
    display: inline-block;
    white-space: nowrap;
    font-size: 12px;
  }

  .quick {
    -webkit-animation: marquee 5s linear infinite;
    animation: marquee 5s linear infinite;
  }
  .middle {
    -webkit-animation: marquee 8s linear infinite;
    animation: marquee 8s linear infinite;
  }
  .slow {
    -webkit-animation: marquee 25s linear infinite;
    animation: marquee 25s linear infinite;
  }
  @-webkit-keyframes marquee {
    0% {
      -webkit-transform: translate3d(0, 0, 0);
    }
    100% {
      -webkit-transform: translate3d(-50%, 0, 0);
    }
  }
  @keyframes marquee {
    0% {
      transform: translateX(0);
    }
    100% {
      transform: translateX(-50%);
    }
  }

  .flex-center {
    display: flex;
    flex: 1;
    justify-content: center;
    margin: 0 auto;
  }
</style>
